﻿using System;
using System.Net;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Communication.Base;

namespace UtilZ.Dotnet.Ex.Communication.Net.DataTransfer.Udp
{
    /// <summary>
    /// UDP客户端初始化参数
    /// </summary>
    public class UdpDataTransferInitPara
    {
        /// <summary>
        /// 接收数据模式
        /// </summary>
        public ThreadMode ReceiveDataMode { get; set; } = ThreadMode.Async;

        /// <summary>
        /// 用于接收数据的本地EndPoint
        /// </summary>
        public EndPoint LocalEndPoint { get; private set; }

        /// <summary>
        /// 接收线程名称
        /// </summary>
        public string ReceiveThreadName { get; set; }
        
        /// <summary>
        /// 发送超时时长,单位:毫秒.大于0有效,小于等于0使用默认值
        /// </summary>
        public int SendMillisecondsTimeout { get; set; } = System.Threading.Timeout.Infinite;

        /// <summary>
        /// 接收超时时长,单位:毫秒.大于0有效,小于等于0使用默认值
        /// </summary>
        public int ReceiveMillisecondsTimeout { get; set; } = System.Threading.Timeout.Infinite;


        private int _receiveBufferSize = NetHelper.MTU_MAX;
        /// <summary>
        /// 接收数据缓冲区大小,默认为一个MTU
        /// </summary>
        public int ReceiveBufferSize
        {
            get { return _receiveBufferSize; }
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(value), "单次接收数据包不能小于等于0");
                }

                _receiveBufferSize = value;
            }
        }

        private int _sendBufferSize = NetHelper.MTU_MAX;
        /// <summary>
        /// 发送数据缓冲区大小,默认为一个MTU
        /// </summary>
        public int SendBufferSize
        {
            get { return _sendBufferSize; }
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(value), "发送缓存不能小于等于0");
                }

                _sendBufferSize = value;
            }
        }

        /// <summary>
        /// udp数据发送最小间隔,单位:100纳秒.小于等于0无间隔
        /// </summary>
        public int SendInterval100NS { get; set; } = 10000;

        /// <summary>
        /// 摘取数据线程数(理论上该值越大大块数据传输越快,但使用CPU和内存资源就越多),小于等于0默认只使用1个线程
        /// </summary>
        public int ThreadCount { get; set; } = 1;



        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="unpacker">分包器</param>
        /// <param name="localEndPoint">接收EndPoint</param>
        /// <exception cref="ArgumentNullException">dataOutput或receiveEndPoint为null将抛出异常</exception>
        public UdpDataTransferInitPara(EndPoint localEndPoint)
        {
            if (localEndPoint == null)
            {
                throw new ArgumentNullException(nameof(localEndPoint));
            }

            this.LocalEndPoint = localEndPoint;
        }
    }
}
